package cn.ffcs.uec.outStaff.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.outStaff.component.bean.UecOutDocEduListboxBean;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.staff.manager.UecDocEduManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecDocEdu;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * @Title:教育经历 CRUD插件
 * @Description:
 * @Copyright: FFCS（C） 2017
 * @Company: FFCS
 * @author Wang Yiren
 * @Version 0.0.1 date:2017年11月27日
 * @since JDK1.6
 */
@Controller
@Scope("prototype")
public class UecOutDocEduListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -5811398149406451671L;
	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	@Getter
	private UecOutDocEduListboxBean bean = new UecOutDocEduListboxBean();
	/**
	 * 人员语言能力实体
	 */
	private UecDocEdu uecDocEdu;
	/**
	 * 翻页查询条件实体
	 */
	private UecDocEdu docEduPaging;

	private UecDocEdu approvalDocEduPaging;
	/**
	 * 人员语言能力查询实体
	 */
	// private UecDocEdu qryUecDocEdu;

	/**
	 * 是否外包人员入职页面引用
	 */
	private boolean isOutStaffEntryExt;
	/**
	 * 入职页面添加的教育经历列表
	 */
	private List<UecDocEdu> eduList = new ArrayList<UecDocEdu>();

	private UecDocEduManager uecEduManager = (UecDocEduManager) ApplicationContextUtil
			.getBean("uecDocEduManager");

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutDocEduListboxExt() {
		Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_DOC_EDU_EXT_LISTBOX_ZUL, this,
				null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.addForward(UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY, this,
				UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY_OF_OUTSTAFF_ENTRY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY_OF_OUTSTAFF_ENTRY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY_OF_OUTSTAFF_ENTRY_VIEW,
				this,
				UecOutStaffConstants.ON_UEC_OUT_DOC_EDU_QUERY_OF_OUTSTAFF_ENTRY_VIEW_RESPONSE);

		this.addForward(UecOutStaffConstants.ON_CLEAN_UEC_OUT_DOC_EDU, this,
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_DOC_EDU_RESPONSE);
	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 选择查询记录
	 * 
	 * @throws Exception
	 */
	// onSelectUecOutDocEduList
	public void onSelectUecOutDocEduList() throws Exception {
		if (this.bean.getUecOutDocEduListbox().getSelectedCount() > 0) {
			uecDocEdu = (UecDocEdu) bean.getUecOutDocEduListbox()
					.getSelectedItem().getValue();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutDocEduQueryResponse(ForwardEvent event) {
		uecOutStaffInfo = (UecOutStaffInfo) event.getOrigin().getData();
		if (null != uecOutStaffInfo) {
		    //设置操作按钮，非盟市主管不可操作按钮
	        /*if(PermissionUtil.isNoMainOutStaff()) {
	            this.setButtonValid(false, true, true, true);
	        }else {
	            this.setButtonValid(false, false, false, false);
	        }*/
			this.setButtonValid(false, true, true, true);
			uecDocEdu = new UecDocEdu();
			uecDocEdu.setStaffId(uecOutStaffInfo.getOutStaffId());
			uecDocEdu.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			docEduPaging = uecDocEdu;			
			this.onQueryUecDocEdu();
		}
	}

	/**
	 * 人员基本信息，抛出事件，事件监听，由外包人员入职Ext抛出
	 * 
	 * @param event
	 */
	public void onUecOutDocEduOfEntryResponse(ForwardEvent event) {
		uecDocEdu = null;
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) event.getOrigin()
				.getData();
		if (null != map) {
			isOutStaffEntryExt = (Boolean) map.get("isOutStaffEntryExt");
			uecOutStaffInfo = (UecOutStaffInfo) map.get("uecOutStaffInfo");
			if (null != uecOutStaffInfo) {
				this.setButtonValid(true, true, true, false);
				ListModel list = new BindingListModelList(eduList, true);
				this.bean.getUecOutDocEduListbox().setModel(list);
				this.bean.getUecOutDocEduListboxPaging().setTotalSize(1);
			}
		}
	}

	/**
	 * 审批中的教育经历id，抛出事件，事件监听，
	 * 
	 * @param event
	 */
	public void onUecOutDocEduOfEntryViewResponse(ForwardEvent event) {
		eduList.clear();
		approvalDocEduPaging = new UecDocEdu();
		String eduIds = (String) event.getOrigin().getData();
		if (!StrUtil.isNullOrEmpty(eduIds)) {
			String[] eduIdArray = eduIds.split("-");
			if (!StrUtil.isNullOrEmpty(eduIdArray) && eduIdArray.length > 0) {
				for (String eduId : eduIdArray) {
					UecDocEdu uecDocEdu = UecDocEdu.newInstance();
					uecDocEdu.setEduId(Long.parseLong(eduId));
					uecDocEdu = uecEduManager.findUecDocEdu(uecDocEdu);
					eduList.add(uecDocEdu);
				}
				onQueryUecDocEdu();
			}

		}

	}

	/**
	 * 清楚变量
	 * 
	 * @param event
	 */
	public void onCleanUecOutDocEduResponse(ForwardEvent event) {
		clearVariable();
		uecOutStaffInfo = null;
		ListboxUtils.clearListbox(this.bean.getUecOutDocEduListbox());
		this.bean.getUecOutDocEduListboxPaging().setTotalSize(1);

		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canView, boolean canAdd,
			boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);
	}

	/**
	 * 查询按钮
	 */
	public void onQueryUecDocEdu() {
		this.bean.getUecOutDocEduListboxPaging().setActivePage(0);
		this.onQueryUecOutDocEduList();
	}

	/**
	 * 重置按钮
	 */
	public void onResetUecDocEdu() {
		ListboxUtils.clearListbox(this.bean.getUecOutDocEduListbox());
		this.bean.getUecOutDocEduListboxPaging().setTotalSize(1);
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void onViewUecOutDocEdu() throws SuspendNotAllowedException,
			Exception {
		if (uecDocEdu != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "view");
			map.put("uecDocEdu", uecDocEdu);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_DOC_EDU_EDIT_ZUL, this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						//
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要查看的记录", "提示信息");
			return;
		}
	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecOutDocEdu() throws Exception {
		if (null != uecOutStaffInfo) {
			if (!isOutStaffEntryExt) {
				boolean isOnTrial = isOnTrial();
				if (!isOnTrial) {
					return;
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "add");
			map.put("uecOutStaffInfo", uecOutStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_DOC_EDU_EDIT_ZUL, this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecDocEdu = (UecDocEdu) event.getData();
						eduList.add(uecDocEdu);
						if (!isOutStaffEntryExt) {
							onQueryUecOutDocEduList();
						} else {
							ListModel list = new BindingListModelList(eduList,
									true);
							bean.getUecOutDocEduListbox().setModel(list);
							bean.getUecOutDocEduListboxPaging().setTotalSize(1);

							postEduList();
						}
					}
				}
			});
		}
	}

	/**
	 * 抛出事件，把添加的列表发送给OutStaffEntryExt
	 */
	private void postEduList() {
		Events.postEvent("onPostEduListOfOutStaffEntry", this, eduList);
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecOutDocEdu() throws Exception, InterruptedException {
		if (uecDocEdu != null) {
			if (!isOutStaffEntryExt) {
				boolean isOnTrial = isOnTrial();
				if (!isOnTrial) {
					return;
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "edit");
			map.put("uecDocEdu", uecDocEdu);
			map.put("uecOutStaffInfo", uecOutStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_DOC_EDU_EDIT_ZUL, this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						if (isOutStaffEntryExt) {
							eduList.remove(uecDocEdu);
						}
						uecDocEdu = (UecDocEdu) event.getData();
						// 新增或修改完成后，列表从数据库更新
						if (!isOutStaffEntryExt) {
							onQueryUecOutDocEduList();
						} else {
							eduList.add(uecDocEdu);
							ListModel list = new BindingListModelList(eduList,
									true);
							bean.getUecOutDocEduListbox().setModel(list);
							bean.getUecOutDocEduListboxPaging().setTotalSize(1);

							postEduList();
						}

					}
				}
			});
		} else {
			ZkUtil.showError("请选中要编辑的记录", "提示信息");
			return;
		}
	}

	/**
	 * 审批驳回中的修改
	 * 
	 * @throws InterruptedException
	 * @throws SuspendNotAllowedException
	 */
	public void onApprovalEditUecOutDocEdu() throws SuspendNotAllowedException,
			InterruptedException {
		if (uecDocEdu != null && uecDocEdu.getId() != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "approvalEdit");
			map.put("uecDocEdu", uecDocEdu);
			map.put("uecOutStaffInfo", uecOutStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_DOC_EDU_EDIT_ZUL, this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						uecDocEdu = (UecDocEdu) event.getData();
						// 新增或修改完成后，列表从数据库更新
						PageInfo pageInfo = uecEduManager
								.queryPageInfoByUecDocEduOnApproval(uecDocEdu,
										bean.getUecOutDocEduListboxPaging()
												.getActivePage() + 1, bean
												.getUecOutDocEduListboxPaging()
												.getPageSize());
						ListModel list = new BindingListModelList(pageInfo
								.getDataList(), true);
						bean.getUecOutDocEduListbox().setModel(list);
						bean.getUecOutDocEduListboxPaging().setTotalSize(1);
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要修改的记录", "提示信息");
			return;
		}

	}

	/**
	 * 删除按钮
	 */
	public void onDelUecOutDocEdu() {
		if (this.uecDocEdu != null && this.uecDocEdu.getId() != null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecDocEdu.removeOnly();
						// PubUtil.reDisplayListbox(bean.getUecOutDocEduListbox(),
						// uecDocEdu, "del");
						onQueryUecOutDocEduList();
						uecDocEdu = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 翻页
	 */
	public void onUecOutDocEduListboxPaging() {
		this.onQueryUecOutDocEduList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecDocEdu = null;
		docEduPaging = null;
		eduList.clear();
	}

	/**
	 * 查询
	 */
	public void onQueryUecOutDocEduList() {
		// 翻页查看生效数据
		if (null != docEduPaging) {
			PageInfo pageInfo = uecEduManager.queryPageInfoByUecDocEdu(
					docEduPaging, this.bean.getUecOutDocEduListboxPaging()
							.getActivePage() + 1, this.bean
							.getUecOutDocEduListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecOutDocEduListbox().setModel(list);
			this.bean.getUecOutDocEduListboxPaging().setTotalSize(
					pageInfo.getTotalCount());

			// 入职 页添加记录后，不选择记录时 点击查询，编辑 按钮 弹出弹窗
			uecDocEdu = null;
		}
		// 翻页查看审批中的数据
		if (null != approvalDocEduPaging) {
//			List<UecDocEdu> pageEdus = getCurrentPageList(eduList, bean
//					.getUecOutDocEduListboxPaging().getActivePage() + 1, bean
//					.getUecOutDocEduListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(eduList, true);
			bean.getUecOutDocEduListbox().setModel(list);
			bean.getUecOutDocEduListboxPaging().setTotalSize(1);

			uecDocEdu = null;
		}
	}

	/**
	 * 判断是否入职
	 * 
	 * @return
	 */
	private boolean isOnTrial() {
		UecTrial qryUecTrial = UecTrial.newInstance();
		qryUecTrial.setStaffId(uecOutStaffInfo.getOutStaffId());
		qryUecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
		if (null == qryUecTrial) {
			ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
			return false;
		}
		return true;
	}

	/**
	 * 根据list 获取当前页list
	 * 
	 * @param list
	 * @param activePage
	 * @param pageSize
	 * @return
	 */
	public List<UecDocEdu> getCurrentPageList(List<UecDocEdu> list, int activePage,
			int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);

	}

}
